package com.atguigu.gulimail.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.feign.MemberFeignService;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimail.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code,HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id","1003917073");
        map.put("client_secret","eee8cb82a3bc50bc3ef6067eac920ac9");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://gulimall.com:20000/oauth2.0/weibo/success");
        map.put("code",code);
        //根据code换取accessToken
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<String,String>(), null, map);
        //处理
        if (response.getStatusLine().getStatusCode()==200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //知道当前是哪个社交用户
            //1。当前用户如果是第一次进网站，自动注册进来（为当前用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）
            //登录或者注册这个社交用户
            R login = memberFeignService.login(socialUser);
            if (login.getCode()==0){
                MemberResponseVo data = login.getData("data", new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功: 用户: {}",data);
                session.setAttribute(AuthServerConstant.LOGIN_USER,data);
                return "redirect:http://gulimall.com:10001/index.html";
            }else {
                return "redirect:http://gulimall.com:20000/login.html";
            }
        }else {
            return "redirect:http://gulimall.com:20000/login.html";
        }
    }
}
